<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增订单</el-button>
        </div>
      </div>
      <vxe-grid v-bind="gridOptions">
        <template #pager>
          <!--使用 pager 插槽-->
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handlePageChange"
          />
        </template>
        <template #operate="scope">
          <el-button
            type="primary"
            icon="edit"
            link
            size="small"
            @click="handleOpenDialog(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleStatusChange(scope.row)"
          >
            {{ scope.row.status == 1 ? "冻结" : "激活" }}
          </el-button>
        </template>
        <template #status="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
            {{ scope.row.status == 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
        <template #time="scope">
          {{ formatDate(scope.row[scope.column.field]) }}
        </template>
      </vxe-grid>

      <!-- 用户表单 -->
      <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        @close="handleCloseDialog"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="订单类型" prop="order_type">
            <el-select v-model="formData.order_type" placeholder="Select">
              <el-option
                v-for="item in DictDataOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户" prop="customer">
            <el-input v-model="formData.customer" placeholder="请输入客户" />
          </el-form-item>
          <el-form-item label="产品料号" prop="product">
            <el-select
              v-model="formData.product"
              filterable
              remote
              reserve-keyword
              placeholder="请输入材料"
              remote-show-suffix
              :remote-method="remoteMethod"
              @change="handleChange"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input v-model="formData.quantity" placeholder="请输入数量" style="width: 100px" />
            <span class="mx-1">{{ unit_name }}</span>
          </el-form-item>
          <el-form-item label="单价" prop="price">
            <el-input v-model="formData.price" placeholder="请输入单价" style="width: 100px" />
          </el-form-item>
          <el-form-item label="交货日期" prop="delivery_date">
            <el-date-picker
              v-model="formData.delivery_date"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注" prop="title">
            <el-input v-model="formData.title" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Sales",
  inherititems: false,
});
import { MaterialOptionType } from "@/api/product/product-bom";
import DictDataAPI from "@/api/system/dict-data";
import SalesOrderAPI, {
  SalesOrderForm,
  SalesOrderPageQuery,
  SalesOrderPageVO,
} from "@/api/order/sales";
import ProductAPI from "@/api/product/product";
import { formatDate } from "@/utils/tools";
const route = useRoute();
const product = ref(route.query.product as unknown as string);
const queryParams = reactive<SalesOrderPageQuery>({
  pageNum: 1,
  pageSize: 10,
});
const unit_name = ref("");
const total = ref(0);
const formRef = ref(ElForm);
const dialog = reactive({
  visible: false,
  title: "新增订单",
});
const productOptions = ref<MaterialOptionType[]>();
const DictDataOptions = ref<OptionType[]>();
const formData = reactive<Partial<SalesOrderForm>>({});
const initFormData: Partial<SalesOrderForm> = {
  id: undefined,
  order_type: DictDataOptions.value?.[0]?.value as number,
  customer: "",
  product: product.value,
  quantity: 0,
  price: 0,
  delivery_date: new Date(),
  is_update: false,
};
const rules = reactive({
  order_type: [{ required: true, message: "订单类型不能为空", trigger: "blur" }],
  product: [{ required: true, message: "编号不能为空", trigger: "blur" }],
  material: [{ required: true, message: "材料不能为空", trigger: "blur" }],
  quantity: [
    {
      pattern: /^\-?([1-9][0-9]*(\.[0-9]{1,4})?|0\.[0-9]{1,4})$/,
      message: "请输入数字",
      trigger: "blur",
    },
    { required: true, message: "数量不能为空", trigger: "blur" },
  ],
  price: [
    {
      pattern: /^([1-9][0-9]*(\.[0-9]{1,4})?|0\.[0-9]{1,4})$/,
      message: "请输入数字",
      trigger: "blur",
    },
    { required: true, message: "单价不能为空", trigger: "blur" },
  ],
  customer: [{ required: true, message: "客户不能为空", trigger: "blur" }],
  delivery_date: [{ required: true, message: "交货日期不能为空", trigger: "blur" }],
});
async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改订单";
    formData.is_update = true;
    SalesOrderAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
      unit_name.value = (data as any).unit_name || "";
    });
  } else {
    Object.assign(formData, initFormData);
    dialog.title = "新增订单";
  }
}
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() || time.getTime() > Date.now() + 3600 * 1000 * 24 * 30 * 6; // 6个月内订单
};
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.id = undefined;
}
const handlePageChange: typeof VxePagerEvents.PageChange = ({
  currentPage,
  pageSize,
}: {
  currentPage: number;
  pageSize: number;
}) => {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  handleQuery();
};
const remoteMethod = async (query: string) => {
  if (query) {
    let options = await ProductAPI.getOptions(query);
    // 将options的label修改为value+label
    options.forEach((item: OptionType) => {
      item.label = `${item.value},${item.label}`;
    });
    productOptions.value = options;
  } else {
    productOptions.value = [];
  }
};
const handleChange = (value: string) => {
  unit_name.value = productOptions.value?.find((item) => item.value === value)?.unit_name || "";
};
// 查询
function handleQuery() {
  gridOptions.loading = true;
  SalesOrderAPI.getPage(queryParams)
    .then((data) => {
      total.value = data.total;
      // 依据 data.list数据price和quantity计算total_price
      data.list.forEach((item) => {
        item.total_price = (item.price ?? 0) * (item.quantity ?? 0);
      });
      gridOptions.data = data.list;
    })
    .finally(() => {
      gridOptions.loading = false;
    });
}
// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const product_id = formData.id as string;
      if (formData.is_update) {
        SalesOrderAPI.update(product_id, formData)
          .then(() => {
            ElMessage.success("修改订单成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      } else {
        SalesOrderAPI.add(formData)
          .then(() => {
            ElMessage.success("新增订单成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      }
    }
  });
}, 1000);
// 重置查询
function handleResetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}
// 激活事件，将用户状态进行修改
function handleStatusChange(row: SalesOrderPageVO) {
  const text = row.status == 0 || row.status == 2 ? "启用" : "停用";
  ElMessageBox.confirm(`确认要${text}该订单吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let status = row.status == 0 || row.status == 2 ? 1 : 2;
    SalesOrderAPI.update(row.id, {
      status: status,
    }).then(() => {
      handleQuery();
      ElMessage.success(`${text}成功`);
    });
  });
}
function getOptions() {
  DictDataAPI.getOptions("order_type").then((data) => {
    DictDataOptions.value = data;
  });
}
// 删除系统配置
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除该项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // SalesOrderAPI.deleteByIds(id as unknown as string).then(() => {
    //   ElMessage.success("删除成功");
    //   // handleQuery();
    //   handleResetQuery();
    // });
  });
}
const gridOptions = reactive<typeof VxeGridProps<SalesOrderPageVO>>({
  border: true,
  loading: false,
  columns: [],
  id: "sales",
  data: [],
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    enabled: true,
    storage: {
      resizable: true,
    },
  },
  height: 700,
});
gridOptions.customConfig = {
  enabled: true,
  storage: {
    resizable: true,
  },
};

// 列配置
gridOptions.columns = [
  { field: "id", title: "订单编号" },
  { field: "order_type_name", title: "订单类型" },
  { field: "customer", title: "客户" },
  { field: "product", title: "产品" },
  { field: "quantity", title: "数量" },
  { field: "unit_name", title: "单位" },
  { field: "price", title: "单价" },
  { field: "total_price", title: "总价" },
  { field: "delivery_date", title: "交货日期" },
  { field: "title", title: "备注" },
  { field: "create_time", title: "建立时间", width: 100, slots: { default: "time" } },
  { field: "update_time", title: "更新时间", width: 100, slots: { default: "time" } },
  { field: "create_user", title: "创建人" },
  { field: "update_user", title: "更新人" },
  { field: "status", title: "状态", width: 80, slots: { default: "status" } },
  { title: "操作", width: 150, slots: { default: "operate" } },
];
onMounted(() => {
  getOptions();
  handleQuery();
});
</script>

<style scoped></style>
